package nps.pay.servlet;

import nps.pay.config.NpsConfig;
import nps.pay.utils.HttpUtils;
import nps.pay.utils.SignUtils;
import okhttp3.Response;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

public class QueryServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String orderNo = req.getParameter("orderNo");
        Map<String, String> dataMap = new LinkedHashMap<>();
        dataMap.put("ORDER_ID", orderNo);//订单号
        dataMap.put("USER_TYPE", "02");//
        dataMap.put("USER_ID", NpsConfig.USER_ID);//
        dataMap.put("SIGN_TYPE", "03");//
        dataMap.put("SIGN", SignUtils.sign(dataMap));

        Response response = HttpUtils.sendRequest(NpsConfig.PAY_URL, dataMap);
        String result = response.body().string();
        System.out.println("代付响应结果：" + result);
        Document reqDoc = null;
        try {
            reqDoc = DocumentHelper.parseText(result);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        Element rootEl = reqDoc.getRootElement();
        String RESP_CODE = rootEl.elementText("RESP_CODE");
        String RESP_DESC = rootEl.elementText("RESP_DESC");
        String STATUS = rootEl.elementText("STATUS");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json; charset=utf-8");
        PrintWriter writer = resp.getWriter();
        Map<String, String> map = new HashMap<>();
        map.put("STATUS", STATUS);
        map.put("RESP_CODE", RESP_CODE);
        map.put("RESP_DESC", RESP_DESC);
        writer.write(map.toString());

    }
}
